package com.voute.View.Activity;

import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.zhouwei.library.CustomPopWindow;
import com.orhanobut.logger.Logger;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Base.BaseFragment;
import com.voute.Model.Action.SelectedHotWordsAction;
import com.voute.Model.Bean.HotWordsBean;
import com.voute.Model.Bean.SearchResultBean;
import com.voute.Model.Bean.SearchResultEntity;
import com.voute.Presenter.ISearchPresenter;
import com.voute.Presenter.Impl.SearchPresenterImpl;
import com.voute.R;
import com.voute.Utils.DisplayUtil;
import com.voute.Utils.RxBus;
import com.voute.Utils.ViewUtils;
import com.voute.View.Adapter.RecommandWordsAdapter;
import com.voute.View.Fragement.HotWordsFragment;
import com.voute.View.IView.ISearchView;

import java.util.ArrayList;

import rx.Subscription;
import rx.functions.Action1;


/**
 * 搜索Activity
 * Created by liukanshan on 2017/1/14.
 */

public class QueryActivity extends BaseActivity implements ISearchView {

    private BaseFragment hot_words_fragment;
    private BaseFragment search_results_fragment;
    private FragmentManager fragmentManager;
    private RelativeLayout back_layout;
    private EditText edt_search;
    private RelativeLayout cancel_layout;
    private boolean show_pop = true;
    Subscription rxSubscription;
    private CustomPopWindow mListPopWindow;
    private View line1;
    private ISearchPresenter presenter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_query;
    }

    @Override
    public void setupView() {
        fragmentManager = getSupportFragmentManager();
        hot_words_fragment = ViewUtils.createFragment(HotWordsFragment.class, true);
        fragmentManager.beginTransaction().add(R.id.frame_layout, hot_words_fragment).commitAllowingStateLoss();
        back_layout = $(R.id.back_layout);
        edt_search = $(R.id.edt_search);
        line1 = $(R.id.line1);
        cancel_layout = $(R.id.cancel_layout);
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                App.GetInstance().finishActivity(QueryActivity.this);
            }
        });

        rxSubscription = RxBus.getDefault().toObservable(SelectedHotWordsAction.class)
                .subscribe(new Action1<SelectedHotWordsAction>() {
                               @Override
                               public void call(SelectedHotWordsAction action) {
                                   show_pop = false;
                                   hidenInput(edt_search);
                                   cancel_layout.setVisibility(View.GONE);
                                   Intent intent=new Intent(QueryActivity.this,SearchResultActivity.class);
                                   intent.putExtra("query_words",action.getSelected_words());
                                   QueryActivity.this.startActivity(intent);
                               }
                           },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                            }
                        });
        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int action_id, KeyEvent keyEvent) {
                if (EditorInfo.IME_ACTION_SEARCH == action_id) {
                    String search_key = edt_search.getText().toString();
                    if (TextUtils.isEmpty(search_key)) {
                        hidenInput(edt_search);
//                        Snackbar.make(edt_search, "搜索内容不能为空", Snackbar.LENGTH_SHORT).show();
                        MaterialDialog notice_dialog = new MaterialDialog.Builder(QueryActivity.this).title("提示").positiveText("确认").cancelable(false).content("搜索内容不能为空").build();
                        notice_dialog.show();
                    } else {
                        cancel_layout.setVisibility(View.GONE);
                        mListPopWindow.dissmiss();
                        Intent intent=new Intent(QueryActivity.this,SearchResultActivity.class);
                        intent.putExtra("query_words",search_key);
                        QueryActivity.this.startActivity(intent);
                    }
                    return true;
                }
                return false;
            }
        });
        cancel_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mListPopWindow!=null){
                    mListPopWindow.dissmiss();
                }
                cancel_layout.setVisibility(View.GONE);
                edt_search.setText("");
            }
        });
        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                Logger.i(editable.toString());
                if (show_pop) {
                    if (!TextUtils.isEmpty(editable.toString())) {
                        presenter.getRecommandSearch(editable.toString());
                        cancel_layout.setVisibility(View.VISIBLE);
                    }
                    else{
                        cancel_layout.setVisibility(View.GONE);
                        if(mListPopWindow!=null){
                            mListPopWindow.dissmiss();
                        }
                    }
                } else {
                    show_pop = !show_pop;
                }
            }
        });
        presenter = new SearchPresenterImpl(this);
    }

    @Override
    public void setupData() {

    }

    @Override
    protected void onDestroy() {
        if (!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
        super.onDestroy();
    }

    private void showPopListView(ArrayList<SearchResultEntity> recommands) {
        if (recommands != null && recommands.size() > 0) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.search_recommand_pop_list, null);
            //处理popWindow 显示内容
            handleListView(contentView, recommands);
            //创建并显示popWindow
            mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                    .create()
                    .showAsDropDown(line1, 0, DisplayUtil.dip2px(this, 0));
            contentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mListPopWindow.dissmiss();
                }
            });
        }
    }

    private void handleListView(View contentView, final ArrayList<SearchResultEntity> recommands) {
        ListView recommandListView = (ListView) contentView.findViewById(R.id.content_list);
        RecommandWordsAdapter adapter = new RecommandWordsAdapter(this, recommands);
        recommandListView.setAdapter(adapter);
        recommandListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mListPopWindow.dissmiss();
                Intent intent=new Intent(QueryActivity.this,SearchResultActivity.class);
                intent.putExtra("query_words",recommands.get(i).getTitle());
                QueryActivity.this.startActivity(intent);
            }
        });
    }

    @Override
    public void setHotWords(HotWordsBean hot_wrod_bean) {

    }

    @Override
    public void setSearchResults(SearchResultBean search_result) {

    }

    @Override
    public void setRecommandSearch(SearchResultBean recommand) {
        if (recommand.getStatus() == 0) {
            ArrayList<SearchResultEntity> datas = new ArrayList<>();
            if(recommand.getData()!=null&&recommand.getData().getFeeds()!=null&&recommand.getData().getFeeds().size()>0){
                datas.addAll(recommand.getData().getFeeds());
                showPopListView(datas);
            }
        } else {
//            Snackbar.make(line1, recommand.getMsg(), Snackbar.LENGTH_SHORT).show();
            MaterialDialog notice_dialog = new MaterialDialog.Builder(QueryActivity.this).title("提示").positiveText("确认").cancelable(false).content(recommand.getMsg()).build();
            notice_dialog.show();
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String errMsg) {
//        Snackbar.make(line1, errMsg, Snackbar.LENGTH_SHORT).show();
        MaterialDialog notice_dialog = new MaterialDialog.Builder(QueryActivity.this).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }
}
